package com.xhwl.centiotdata.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.phonogram.PhonogramIntegrationFactory;
import com.xhwl.centiotdata.handler.phonogram.PhonogramIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.brodcast.PhonogramConfigDTO;
import com.xhwl.centiotdata.service.IBoardcastService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.centiotdata.service.cent.ISpaceCentService;
import com.xhwl.centiotdata.service.integrateconfig.PhonogramIntegrationConfig;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.iotdata.haikang.BroadcastDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.query.cent.device.DeviceQuery;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.query.cent.sdata.SpaceQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author pengjunming
 * @description
 * @date 2022/9/28 10:58
 */
@Service
@Slf4j
public class BoardcastServiceImpl implements IBoardcastService {

    @Resource
    private IDeviceCentService iDeviceCentService;

    @Resource
    private PhonogramIntegrationConfig integrationConfig;

    @Autowired
    private IProjectCentService projectCentService;

    @Autowired
    private ISpaceCentService spaceCentService;

    @Override
    public ResultJson broadcast(BroadcastDTO dto) {

        if(dto.getProjectId() == null){
            throw new BusinessException("项目id信息为空，即projectId");
        }
        if(dto.getPositionId() == null){
            throw new BusinessException("组织code信息为空，即positionId");
        }
        //通过传送的组织编码来查询组织id
        Integer orgId = this.orgCodeForOrgId(dto.getPositionId(), dto.getProjectId());

        DevicePageQuery devicePageQuery = new DevicePageQuery();
        devicePageQuery.setOrganizationId(orgId);
        devicePageQuery.setCategoryIdList(Collections.singletonList(CategoryEnum.PHONOGRAM_SYSTEM.getId()));
        devicePageQuery.setProjectId(dto.getProjectId());
        try {
            //获取设备信息
            List<DeviceDTO> deviceDTOList = iDeviceCentService.listDevice(null, devicePageQuery);
            if (!CollectionUtils.isEmpty(deviceDTOList)) {
                DeviceDTO deviceDTO = deviceDTOList.get(0);
                Integer projectId = deviceDTO.getProjectId();
                Integer productId = deviceDTO.getProductId();
                PhonogramIntegrationHandler handler = PhonogramIntegrationFactory.getInvokeStrategy(productId);
                if (Objects.nonNull(handler)) {
                    // 获取音柱配置
                    List<PhonogramConfigDTO> configIntegrationConfig = integrationConfig.getIntegrationConfig(projectId);
                    configIntegrationConfig.forEach(config -> {
                        for (DeviceDTO deviceDTO1 : deviceDTOList) {
                            handler.customBroadCast(config, dto, deviceDTO1);
                        }
                    });
                }
                return ResultJson.success();
            } else {
                return ResultJson.fail("设备不存在");
            }
        } catch (Exception e) {
            log.error("广播失败", e);
            return ResultJson.fail(e.getMessage());
        }
    }

    /**
     * 通过传的组织编码，来查询组织id
     */
    private Integer orgCodeForOrgId(String orgCode, Integer projectId){
        OrganizationQuery organizationQuery = new OrganizationQuery();
        organizationQuery.setProjectIds(Collections.singletonList(projectId));
        List<Organization> organizationList = projectCentService.organizationList(organizationQuery);
        //先在组织表中查询，看这个code是否存在
        Organization organization1 = organizationList.stream().filter(organization -> {
            if (StringUtils.equals(orgCode, organization.getCode())) {
                return true;
            } else {
                return false;
            }
        }).findAny().orElse(null);
        if(organization1 != null){
            return organization1.getId();
        }else{
            //执行这里，表示组织表中不存在这个code，需要到space中查询
            ResultJson resultJson = spaceCentService.list(new SpaceQuery());
            if(resultJson == null || !resultJson.getState()){
                throw new BusinessException("获取空间信息的接口异常");
            }
            JSONArray spaceArray = JSONObject.parseArray(JSONObject.toJSONString(resultJson.getResult()));
            Object spaceObject1 = spaceArray.stream().filter(object -> {
                JSONObject spaceObject = JSONObject.parseObject(object.toString());
                JSONObject codeObject = JSONObject.parseObject(spaceObject.getString("data"));
                if (StringUtils.equals(
                        String.valueOf(spaceObject.getInteger("projectId")),
                        String.valueOf(projectId)) &&
                        StringUtils.equals(
                                codeObject.getString("code"), orgCode
                        )) {
                    return true;
                } else {
                    return false;
                }
            }).findAny().orElse(null);
            if(spaceObject1 == null){
                throw new BusinessException("通过该组织编码未找到相应的组织信息");
            }
            return JSONObject.parseObject(spaceObject1.toString()).getInteger("organizationId");
        }
    }
}
